<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.2.1">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/%E6%AD%A6%E6%B1%8932x32.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/%E6%AD%A6%E6%B1%8916x16.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib1/font-awesome/css/all.min.css">
  <link rel="stylesheet" href="/lib1/pace/pace-theme-center-simple.min.css">
  <script src="/lib1/pace/pace.min.js"></script>

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"example.com","root":"/","scheme":"Gemini","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":true,"show_result":true,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="前言如题，打算使用JS从头开始刷leetcode，大致地记录并讲解一下自己的解题思路吧，由于自己的水平原因，所以思路与解法都会比较偏新手向吧，同时不会只关注这一个题的思路，会有一些整体的思路与延伸吧。做这个记录的原因主要是想以新手的角度讲下自己解题遇到的弯路，同时也给自己加深印象吧。开始时可能注释会有些啰嗦，后续会减少不必要的代码解释。打算先写完并理解前150题吧，也并不打算分类的，因为前百题的思">
<meta property="og:type" content="article">
<meta property="og:title" content="JS力扣刷题记（一）">
<meta property="og:url" content="http://example.com/2021/09/06/%E7%AE%97%E6%B3%95/JS%E5%8A%9B%E6%89%A3%E5%88%B7%E9%A2%98%E8%AE%B0%EF%BC%88%E4%B8%80%EF%BC%89/index.html">
<meta property="og:site_name" content="Technological Blog">
<meta property="og:description" content="前言如题，打算使用JS从头开始刷leetcode，大致地记录并讲解一下自己的解题思路吧，由于自己的水平原因，所以思路与解法都会比较偏新手向吧，同时不会只关注这一个题的思路，会有一些整体的思路与延伸吧。做这个记录的原因主要是想以新手的角度讲下自己解题遇到的弯路，同时也给自己加深印象吧。开始时可能注释会有些啰嗦，后续会减少不必要的代码解释。打算先写完并理解前150题吧，也并不打算分类的，因为前百题的思">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2021-09-06T08:12:42.000Z">
<meta property="article:modified_time" content="2021-09-29T15:18:39.320Z">
<meta property="article:author" content="Li Yudong">
<meta property="article:tag" content="力扣">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="http://example.com/2021/09/06/%E7%AE%97%E6%B3%95/JS%E5%8A%9B%E6%89%A3%E5%88%B7%E9%A2%98%E8%AE%B0%EF%BC%88%E4%B8%80%EF%BC%89/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>JS力扣刷题记（一） | Technological Blog</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">Technological Blog</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">IT小白的成长之旅</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-about">

    <a href="/about/" rel="section"><i class="user fa-fw"></i>关于</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="tags fa-fw"></i>标签<span class="badge">18</span></a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="th fa-fw"></i>分类<span class="badge">14</span></a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="archive fa-fw"></i>归档<span class="badge">95</span></a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

  <a href="https://github.com/tiarmor1" class="github-corner" title="Follow me on GitHub" aria-label="Follow me on GitHub" rel="noopener" target="_blank"><svg width="80" height="80" viewBox="0 0 250 250" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://example.com/2021/09/06/%E7%AE%97%E6%B3%95/JS%E5%8A%9B%E6%89%A3%E5%88%B7%E9%A2%98%E8%AE%B0%EF%BC%88%E4%B8%80%EF%BC%89/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/author.jpg">
      <meta itemprop="name" content="Li Yudong">
      <meta itemprop="description" content="">
    </span>
    
    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Technological Blog">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          JS力扣刷题记（一）
        </h1>
    
        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>
    
              <time title="创建时间：2021-09-06 16:12:42" itemprop="dateCreated datePublished" datetime="2021-09-06T16:12:42+08:00">2021-09-06</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2021-09-29 23:18:39" itemprop="dateModified" datetime="2021-09-29T23:18:39+08:00">2021-09-29</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/%E7%AE%97%E6%B3%95/" itemprop="url" rel="index"><span itemprop="name">算法</span></a>
                </span>
            </span>
    
          
    
        </div>
      </header>
    
    
    
    
    <div class="post-body" itemprop="articleBody">
    
      
        <h2 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h2><p>如题，打算使用JS从头开始刷leetcode，大致地记录并讲解一下自己的解题思路吧，由于自己的水平原因，所以思路与解法都会比较偏新手向吧，同时不会只关注这一个题的思路，会有一些整体的思路与延伸吧。做这个记录的原因主要是想以新手的角度讲下自己解题遇到的弯路，同时也给自己加深印象吧。开始时可能注释会有些啰嗦，后续会减少不必要的代码解释。打算先写完并理解前150题吧，也并不打算分类的，因为前百题的思路都是经典解题思路，都需要慢慢体会吧。</p>
<h2 id="1、两数之和"><a href="#1、两数之和" class="headerlink" title="1、两数之和"></a>1、两数之和</h2><p>给定一个整数数组 nums 和一个整数目标值 target，请你在该数组中找出 和为目标值 的那 两个整数，并返回它们的数组下标。你可以假设每种输入只会对应一个答案。但是，数组中同一个元素不能使用两遍。你可以按任意顺序返回答案。转载自<a href="https://leetcode-cn.com/problems/two-sum/" target="_blank" rel="noopener">两数之和</a></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">&#123;number[]&#125;</span> <span class="variable">nums</span></span></span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">&#123;number&#125;</span> <span class="variable">target</span></span></span></span><br><span class="line"><span class="comment"> * <span class="doctag">@return <span class="type">&#123;number[]&#125;</span></span></span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">const</span> twoSum = <span class="function">(<span class="params">nums, target</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">let</span> res = [];</span><br><span class="line">    <span class="keyword">let</span> map = <span class="keyword">new</span> <span class="built_in">Map</span>();</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; nums.length; i++) &#123;</span><br><span class="line">        map.set(nums[i], i);</span><br><span class="line">        <span class="comment">//很简单的题目与逻辑，用map即哈希表的方法辅助查找即可，使用map的set方法构建。</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; nums.length; i++) &#123;</span><br><span class="line">        <span class="keyword">let</span> newTarget = target - nums[i];</span><br><span class="line">        <span class="keyword">if</span> (map.has(newTarget) &amp;&amp; (map.get(newTarget) !== i)) &#123;</span><br><span class="line">            res.push(i, map.get(newTarget));</span><br><span class="line">            <span class="comment">//使用has、get方法分别判断与获取索引</span></span><br><span class="line">            <span class="comment">//这里要注意下，不能两个相同索引相加</span></span><br><span class="line">            <span class="keyword">return</span> res;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="2、两数相加"><a href="#2、两数相加" class="headerlink" title="2、两数相加"></a>2、两数相加</h2><p>给你两个非空 的链表，表示两个非负的整数。它们每位数字都是按照 逆序 的方式存储的，并且每个节点只能存储 一位 数字。请你将两个数相加，并以相同形式返回一个表示和的链表。你可以假设除了数字 0 之外，这两个数都不会以 0 开头。转载至<a href="https://leetcode-cn.com/problems/add-two-numbers/" target="_blank" rel="noopener">两数之和</a></p>
<p>例：输入：l1 = [2,4,3], l2 = [5,6,4]；输出：[7,0,8]；解释：342 + 465 = 807。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Definition for singly-linked list.</span></span><br><span class="line"><span class="comment"> * function ListNode(val) &#123;</span></span><br><span class="line"><span class="comment"> *     this.val = val;</span></span><br><span class="line"><span class="comment"> *     this.next = null;</span></span><br><span class="line"><span class="comment"> * &#125;</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">&#123;ListNode&#125;</span> <span class="variable">l1</span></span></span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">&#123;ListNode&#125;</span> <span class="variable">l2</span></span></span></span><br><span class="line"><span class="comment"> * <span class="doctag">@return <span class="type">&#123;ListNode&#125;</span></span></span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">const</span> addTwoNumbers = <span class="function"><span class="keyword">function</span>(<span class="params">l1, l2</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">let</span> carry = <span class="number">0</span>;</span><br><span class="line">    <span class="comment">//定义进位，</span></span><br><span class="line">    <span class="keyword">let</span> sum = <span class="keyword">new</span> ListNode(<span class="number">0</span>);</span><br><span class="line">    <span class="comment">//一般链表题目的输出，需要先新建一个空的头节点，之后以该空结点作链表处理，从而能够避免因链表长度不够导致的报错,后续返回head.next</span></span><br><span class="line">    <span class="keyword">let</span> head = sum;</span><br><span class="line">    <span class="keyword">while</span> (l1 || l2 || carry) &#123;</span><br><span class="line">        <span class="keyword">let</span> value1 = ((l1 === <span class="literal">null</span>) ? <span class="number">0</span> : l1.val);</span><br><span class="line">        <span class="comment">//其实是在往前面补0，以确保两个加数位数一致</span></span><br><span class="line">        <span class="keyword">let</span> value2 = ((l2 === <span class="literal">null</span>) ? <span class="number">0</span> : l2.val);</span><br><span class="line">        sum.next = <span class="keyword">new</span> ListNode((value1 + value2 + carry) % <span class="number">10</span>);</span><br><span class="line">        carry = ((value1 + value2 + carry) &gt;= <span class="number">10</span> ? <span class="number">1</span> : <span class="number">0</span>);</span><br><span class="line">        sum = sum.next;</span><br><span class="line">        <span class="keyword">if</span> (l1) l1 = l1.next;</span><br><span class="line">        <span class="keyword">if</span> (l2) l2 = l2.next;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> head.next;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>一般情况下，除了用链表来存储大数以外，在JS中更常用的是用字符串来保存，因此下面我们写一个字符串类型的大数相加，基本的逻辑和链表是一样的，主要是处理的方式不同，这里我就不再赘述原理了。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> add = <span class="function"><span class="keyword">function</span> <span class="title">add</span>(<span class="params">a, b</span>)</span>&#123;</span><br><span class="line">  <span class="keyword">let</span> m = <span class="string">""</span>;</span><br><span class="line">  <span class="keyword">let</span> n = <span class="string">""</span>;</span><br><span class="line">  <span class="keyword">let</span> res = [];</span><br><span class="line">  <span class="keyword">let</span> sum = <span class="number">0</span>;</span><br><span class="line">  <span class="keyword">if</span> (a.length &gt; b.length)&#123;</span><br><span class="line">    a = <span class="string">'0'</span> + a;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> i = b.length; i &lt; a.length; i++)&#123;</span><br><span class="line">      b = <span class="string">'0'</span> + b;</span><br><span class="line">    &#125;</span><br><span class="line">    m = a.split(<span class="string">''</span>);</span><br><span class="line">    n = b.split(<span class="string">''</span>);</span><br><span class="line">  &#125; </span><br><span class="line">  <span class="keyword">else</span> &#123;</span><br><span class="line">    b = <span class="string">'0'</span> + b;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> i = a.length; i &lt; b.length; i++)&#123;</span><br><span class="line">      a = <span class="string">'0'</span> + a;</span><br><span class="line">    &#125;</span><br><span class="line">    a = a.split(<span class="string">''</span>);</span><br><span class="line">    b = b.split(<span class="string">''</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">let</span> i = a.length - <span class="number">1</span>; i &gt;= <span class="number">0</span>; i--) &#123;</span><br><span class="line">    <span class="keyword">let</span> k = (<span class="built_in">parseInt</span>(a[i]) + <span class="built_in">parseInt</span>(b[i]) + sum) % <span class="number">10</span>;</span><br><span class="line">        res.unshift(k);</span><br><span class="line">        <span class="keyword">if</span> ((<span class="built_in">parseInt</span>(a[i]) + <span class="built_in">parseInt</span>(b[i]) + sum) &gt;= <span class="number">10</span>) &#123;</span><br><span class="line">            <span class="keyword">if</span> ((m === n) &amp;&amp; (i = t)) &#123;</span><br><span class="line">                res.unshift(<span class="string">"1"</span>);</span><br><span class="line">            &#125;</span><br><span class="line">            sum = <span class="number">1</span></span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            sum = <span class="number">0</span>;</span><br><span class="line">        &#125;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">let</span> ans = res.join(<span class="string">""</span>);</span><br><span class="line">  <span class="keyword">return</span> ans;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="3、无重复字符的最长子串"><a href="#3、无重复字符的最长子串" class="headerlink" title="3、无重复字符的最长子串"></a>3、无重复字符的最长子串</h2><p>题目：给定一个字符串，请你找出其中不含有重复字符的 <strong>最长子串</strong> 的长度。</p>
<p>例如：输入: s = “abcabcbb”。输出: 3 。解释: 因为无重复字符的最长子串是 “abc”，所以其长度为 3。</p>
<p>思路：像这种子串的问题，最小覆盖子串、字符串的排列、找到字符串中所有字母异位词、无重复字符的最长子串。其实思路基本一致，子串的问题基本都能用滑动窗口的思想来解决。滑动窗口就是双指针的进阶版吧，即维护一个窗口，不断滑动并更新答案。</p>
<p><em><strong>1、</strong></em>我们在字符串<code>S</code>中使用双指针中的左右指针技巧，初始化<code>left = right = 0</code>，把索引左闭右开区间<code>[left, right)</code>称为一个「窗口」。</p>
<p><em><strong>2、</strong></em>我们先不断地增加<code>right</code>指针扩大窗口<code>[left, right)</code>，直到窗口中的字符串符合要求（包含了<code>T</code>中的所有字符）。</p>
<p><em><strong>3、</strong></em>此时，我们停止增加<code>right</code>，转而不断增加<code>left</code>指针缩小窗口<code>[left, right)</code>，直到窗口中的字符串不再符合要求（不包含<code>T</code>中的所有字符了）。同时，每次增加<code>left</code>，我们都要更新一轮结果。</p>
<p><em><strong>4、</strong></em>重复第 2 和第 3 步，直到<code>right</code>到达字符串<code>S</code>的尽头</p>
<p><strong>第 2 步相当于在寻找一个「可行解」，然后第 3 步在优化这个「可行解」，最终找到最优解，</strong>也就是最短的覆盖子串。左右指针轮流前进，窗口大小增增减减，窗口不断向右滑动，这就是「滑动窗口」这个名字的来历。下面画图理解一下，<code>needs</code>和<code>window</code>相当于计数器，分别记录<code>T</code>中字符出现次数和「窗口」中的相应字符的出现次数。v</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">&#123;string&#125;</span> <span class="variable">s</span></span></span></span><br><span class="line"><span class="comment"> * <span class="doctag">@return <span class="type">&#123;number&#125;</span></span></span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">const</span> lengthOfLongestSubstring = <span class="function"><span class="keyword">function</span>(<span class="params">s</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">let</span> right = <span class="number">0</span>, left = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">let</span> length = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">let</span> arr = [];</span><br><span class="line">    <span class="comment">//本题的关键在于如何判断是否无重复子串，用indexOf判断新进项即可，或者直接用for循环判断</span></span><br><span class="line">    <span class="keyword">while</span> (right &lt; s.length) &#123;</span><br><span class="line">        <span class="keyword">let</span> index = arr.indexOf(s[right]);</span><br><span class="line">        <span class="keyword">if</span> (index !== <span class="number">-1</span>) &#123;</span><br><span class="line">            arr.splice(<span class="number">0</span>, index + <span class="number">1</span>);</span><br><span class="line">            <span class="comment">//将重复项之前全部删除,这里其实我们用字符串的操作来代替了滑动窗口的左移</span></span><br><span class="line">        &#125;</span><br><span class="line">        arr.push(s[right]);</span><br><span class="line">        length = <span class="built_in">Math</span>.max(length, arr.length);</span><br><span class="line">        right++;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> length;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<h2 id="4、寻找正序数组的两个中位数"><a href="#4、寻找正序数组的两个中位数" class="headerlink" title="4、寻找正序数组的两个中位数"></a>4、寻找正序数组的两个中位数</h2><p>题目：给定两个大小为 m 和 n 的正序（从小到大）数组 nums1 和 nums2。请你找出并返回这两个正序数组的中位数。进阶：你能设计一个时间复杂度为 O(log (m+n)) 的算法解决此问题吗？</p>
<p>思路：暴力求解的话极其简单，直接for循环即可，第一时间会想到就是归并排序最后一步。按照 O(log (m+n)) 时间复杂度的话，面对有序数组的排序，首先想到二分查找，见下方，但是对于两个数组的二分查找该如何实现。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">binary_search</span>(<span class="params">arr,low, high, key</span>) </span>&#123;</span><br><span class="line">            <span class="keyword">if</span> (low &gt; high)&#123;</span><br><span class="line">                <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">var</span> mid = <span class="built_in">parseInt</span>((high + low) / <span class="number">2</span>);</span><br><span class="line">            <span class="keyword">if</span>(arr[mid] == key)&#123;</span><br><span class="line">                <span class="keyword">return</span> mid;</span><br><span class="line">            &#125;<span class="keyword">else</span> <span class="keyword">if</span> (arr[mid] &gt; key)&#123;</span><br><span class="line">                high = mid - <span class="number">1</span>;</span><br><span class="line">                <span class="keyword">return</span> binary_search(arr, low, high, key);</span><br><span class="line">            &#125;<span class="keyword">else</span> <span class="keyword">if</span> (arr[mid] &lt; key)&#123;</span><br><span class="line">                low = mid + <span class="number">1</span>;</span><br><span class="line">                <span class="keyword">return</span> binary_search(arr, low, high, key);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;;</span><br></pre></td></tr></table></figure>

<p>该题的本质可扩展为寻找两个有序数组的第k小数，不一定是中位数，因此二分查找的本质是partition，每次都剔除k/2个数，且保证这些数都在第k小数左边，即都比第k小数小，然后k = k/2；递归处理后，得到第k小数。</p>
<p>二分查找，关键点在于要partition两个排好序的数组成左右两等份，partition需要满足len(Aleft)+len(Bleft)=(m+n+1)/2 - m是数组A的长度， n是数组B的长度并且partition后 A左边最大(maxLeftA), A右边最小（minRightA), B左边最大（maxLeftB), B右边最小（minRightB) 满足(maxLeftA &lt;= minRightB &amp;&amp; maxLeftB &lt;= minRightA)有了这两个条件，那么median就在这四个数中，根据奇数或者是偶数。</p>
<p>奇数：median = max(maxLeftA, maxLeftB)；偶数：median = (max(maxLeftA, maxLeftB) + min(minRightA, minRightB)) / 2。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 二分解法</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">&#123;number[]&#125;</span> <span class="variable">nums1</span></span></span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">&#123;number[]&#125;</span> <span class="variable">nums2</span></span></span></span><br><span class="line"><span class="comment"> * <span class="doctag">@return <span class="type">&#123;number&#125;</span></span></span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">var</span> findMedianSortedArrays = <span class="function"><span class="keyword">function</span>(<span class="params">nums1, nums2</span>) </span>&#123;</span><br><span class="line">  <span class="comment">// 确保nums1为更短的字符串</span></span><br><span class="line">  <span class="keyword">if</span> (nums1.length &gt; nums2.length) &#123;</span><br><span class="line">    <span class="keyword">return</span> findMedianSortedArrays(nums2, nums1);</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">const</span> m = nums1.length</span><br><span class="line">  <span class="keyword">const</span> n = nums2.length</span><br><span class="line">  <span class="keyword">let</span> low = <span class="number">0</span></span><br><span class="line">  <span class="keyword">let</span> high = m</span><br><span class="line">  <span class="keyword">while</span>(low &lt;= high) &#123;</span><br><span class="line">    <span class="keyword">const</span> i = low + <span class="built_in">Math</span>.floor((high - low) / <span class="number">2</span>)</span><br><span class="line">    <span class="keyword">const</span> j = <span class="built_in">Math</span>.floor((m + n + <span class="number">1</span>) / <span class="number">2</span>) - i</span><br><span class="line"></span><br><span class="line">    <span class="keyword">const</span> maxLeftA = i === <span class="number">0</span> ? -<span class="literal">Infinity</span> : nums1[i<span class="number">-1</span>]</span><br><span class="line">    <span class="keyword">const</span> minRightA = i === m ? <span class="literal">Infinity</span> : nums1[i]</span><br><span class="line">    <span class="keyword">const</span> maxLeftB = j === <span class="number">0</span> ? -<span class="literal">Infinity</span> : nums2[j<span class="number">-1</span>]</span><br><span class="line">    <span class="keyword">const</span> minRightB = j === n ? <span class="literal">Infinity</span> : nums2[j]</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (maxLeftA &lt;= minRightB &amp;&amp; minRightA &gt;= maxLeftB) &#123;</span><br><span class="line">      <span class="keyword">return</span> (m + n) % <span class="number">2</span> === <span class="number">1</span></span><br><span class="line">        ? <span class="built_in">Math</span>.max(maxLeftA, maxLeftB)</span><br><span class="line">        : (<span class="built_in">Math</span>.max(maxLeftA, maxLeftB) + <span class="built_in">Math</span>.min(minRightA, minRightB)) / <span class="number">2</span></span><br><span class="line">    &#125; <span class="keyword">else</span> <span class="keyword">if</span> (maxLeftA &gt; minRightB) &#123;</span><br><span class="line">      high = i - <span class="number">1</span></span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">      low = low + <span class="number">1</span></span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>



<h2 id="5、最长回文子串"><a href="#5、最长回文子串" class="headerlink" title="5、最长回文子串"></a>5、最长回文子串</h2><p>题目：给你一个字符串 s，找到 s中最长的回文子串。</p>
<p>思路：最长回文子串的关键，其实通过双指针法也可以来处理，根据上题所述的思路很好进行解决，关键在于如何判定是否是回文子串的函数。但回文子串以及后序的回文子序列等问题，由于前后文联系比较紧密，且多次判断是否符合时间复杂度较大，通常使用动态规划来进行求解。</p>
<p>动态转移方程：dp[i] [j] = dp[i+1] [j-1] &amp;&amp; (dp[i] === dp[j])；dp[i] [j]为true指的是：从i到j是回文串。</p>
<p>初始条件：即字符串长度仅为0、1时，必为回文子串，由于有这样的初始条件，初始项比较多，动态转移方程需要修改成:dp[i] [j] = (dp[i] === dp[j] &amp;&amp; (j - i &lt; 2 || dp[i+1] dp[j - 1]))。同样，由于初始条件必然有j &gt; i，像这种初始条件的dp，一般都会使用斜向遍历。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">&#123;string&#125;</span> <span class="variable">s</span></span></span></span><br><span class="line"><span class="comment"> * <span class="doctag">@return <span class="type">&#123;string&#125;</span></span></span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">const</span> longestPalindrome = <span class="function"><span class="keyword">function</span>(<span class="params">s</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">let</span> res = <span class="string">""</span>;</span><br><span class="line">    <span class="keyword">let</span> dp = <span class="built_in">Array</span>.from(<span class="keyword">new</span> <span class="built_in">Array</span>(s.length), () =&gt; <span class="keyword">new</span> <span class="built_in">Array</span>(s.length).fill(<span class="number">0</span>));</span><br><span class="line">    <span class="comment">//利用Array.from构建二维数组，或者使用for循环也可</span></span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> i = s.length - <span class="number">1</span>; i &gt;= <span class="number">0</span>; i--) &#123;</span><br><span class="line">        <span class="comment">//这里由于动态转移方程中dp[i][..]依赖于dp[i + 1][..]，因此需要倒着遍历来简化操作</span></span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">let</span> j = i; j &lt; s.length; j++) &#123;</span><br><span class="line">            <span class="comment">//同样，由于初始条件原因，j从靠近i到远离i来遍历</span></span><br><span class="line">            dp[i][j] = ((s[i] === s[j]) &amp;&amp; (j - i &lt; <span class="number">2</span> || dp[i+<span class="number">1</span>][j<span class="number">-1</span>]));</span><br><span class="line">            <span class="keyword">if</span> (dp[i][j] &amp;&amp; (j - i + <span class="number">1</span> &gt; res.length)) &#123;</span><br><span class="line">                res = s.substring(i, j+<span class="number">1</span>);</span><br><span class="line">                <span class="comment">//substring截取字符串，包头不包尾</span></span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> res;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="6、Z字形变换"><a href="#6、Z字形变换" class="headerlink" title="6、Z字形变换"></a>6、Z字形变换</h2><p>题目：将一个给定字符串 s 根据给定的行数 numRows ，以从上往下、从左到右进行 Z 字形排列。比如输入字符串为 “PAYPALISHIRING” 行数为 3 时，排列如下：之后，你的输出需要从左往右逐行读取，产生出一个新的字符串，比如：”PAHNAPLSIIGYIR”。请你实现这个将字符串进行指定行数变换的函数：let convert(string s, int numRows)。</p>
<p> P     A     H     N<br>        A  P L S  I   I  G<br>        Y     I      R</p>
<p>思路：关键在于找规律，中间列每列一个，且列数为numsRows-2；因此将一个第一列与后续的中间列作为一个循环，个数为numsRows + numsRows - 2。这样一个循环就能找出来了，再根据每个字符在循环中的位置，分别将其置入不同行。其中仅循环的第一位为第一行，V形排列。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> convert = <span class="function"><span class="keyword">function</span>(<span class="params">s, numRows</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (numRows === <span class="number">1</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> s;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">let</span> rows = <span class="keyword">new</span> <span class="built_in">Array</span>(numRows).fill(<span class="string">""</span>);<span class="comment">//用数组依次存储每一行的字符</span></span><br><span class="line">    <span class="keyword">let</span> circle = (<span class="number">2</span> * numRows - <span class="number">2</span>);</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; s.length; i++) &#123;</span><br><span class="line">        <span class="keyword">let</span> x = i % circle;</span><br><span class="line">        rows[<span class="built_in">Math</span>.min(x, circle - x)] += s[i];</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">let</span> ans = rows.join(<span class="string">""</span>);</span><br><span class="line">    <span class="keyword">return</span> ans;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="7、整数反转"><a href="#7、整数反转" class="headerlink" title="7、整数反转"></a>7、整数反转</h2><p>题目：给出一个 32 位的有符号整数，你需要将这个整数中每位上的数字进行反转。</p>
<p>思路：在先判断正负号之后，用转字符串再转数组后，使用reverse()方法可以简单实现，但可以思考下用数学方法要如何处理。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//先试一下数组反转，可以轻松解决</span></span><br><span class="line"><span class="keyword">let</span> reverse = <span class="function"><span class="keyword">function</span>(<span class="params">x</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">let</span> res = x.toString().split(<span class="string">""</span>);</span><br><span class="line">    <span class="keyword">if</span> (res[<span class="number">0</span>] == <span class="string">"-"</span>) &#123;</span><br><span class="line">        res.push(<span class="string">"-"</span>);<span class="comment">//反转后，相当于在前面加-，后面的负号parseInt会忽略掉</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">let</span> ans = <span class="built_in">parseInt</span>(res.reverse().join(<span class="string">""</span>));</span><br><span class="line">    <span class="keyword">if</span> (ans &gt;= <span class="built_in">Math</span>.pow(<span class="number">2</span>, <span class="number">31</span>) || ans &lt;= -<span class="built_in">Math</span>.pow(<span class="number">2</span>, <span class="number">31</span>)) &#123;</span><br><span class="line">        ans = <span class="number">0</span>;</span><br><span class="line">    &#125;ue</span><br><span class="line">    <span class="keyword">return</span> ans;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//再试一下数学方法，关键在于一位位地取余数</span></span><br><span class="line"><span class="keyword">let</span> reverse = <span class="function"><span class="keyword">function</span>(<span class="params">x</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">let</span> result = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">while</span> (x !== <span class="number">0</span>) &#123;</span><br><span class="line">        result = x % <span class="number">10</span> + result * <span class="number">10</span>;</span><br><span class="line">        x = (x / <span class="number">10</span>) | <span class="number">0</span>;</span><br><span class="line">        <span class="comment">//通过位运算符保证取整(无论正负)，同时强制转换为32位有符号整数</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> (result | <span class="number">0</span>) === result ? result : <span class="number">0</span>;</span><br><span class="line">    <span class="comment">//result | 0 超过32位的整数转换结果不等于自身，可用作溢出判断。</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="8、字符串转整数"><a href="#8、字符串转整数" class="headerlink" title="8、字符串转整数"></a>8、字符串转整数</h2><p>题目：请你来实现一个 atoi 函数，使其能将字符串转换成整数。</p>
<p>首先，该函数会根据需要丢弃无用的开头空格字符，直到寻找到第一个非空格的字符为止。接下来的转化规则如下：</p>
<p>如果第一个非空字符为正或者负号时，则将该符号与之后面尽可能多的连续数字字符组合起来，形成一个有符号整数。</p>
<p>假如第一个非空字符是数字，则直接将其与之后连续的数字字符组合起来，形成一个整数。</p>
<p>该字符串在有效的整数部分之后也可能会存在多余的字符，那么这些字符可以被忽略，它们对函数不应该造成影响。</p>
<p>假如该字符串中的第一个非空格字符不是一个有效整数字符、字符串为空或字符串仅包含空白字符时，则你的函数不需要进行转换，即无法进行有效转换。在任何情况下，若函数不能进行有效的转换时，请返回 0 。</p>
<p>注意：本题中的空白字符只包括空格字符 ‘ ‘ 。假设我们的环境只能存储 32 位大小的有符号整数。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//像这种字符串匹配的，先想到使用正则即可，先用trim来去掉前后的空格</span></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">&#123;string&#125;</span> <span class="variable">s</span></span></span></span><br><span class="line"><span class="comment"> * <span class="doctag">@return <span class="type">&#123;number&#125;</span></span></span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">var</span> myAtoi = <span class="function"><span class="keyword">function</span>(<span class="params">s</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">const</span> re = <span class="keyword">new</span> <span class="built_in">RegExp</span>(<span class="regexp">/^(-|\+)?\d+/</span>);</span><br><span class="line">    <span class="keyword">let</span> str = s.trim().match(re);</span><br><span class="line">    <span class="keyword">let</span> res = str ? <span class="built_in">Number</span>(str[<span class="number">0</span>]) : <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">return</span> res &gt;= <span class="number">0</span> ? <span class="built_in">Math</span>.min(res, <span class="number">2</span>**<span class="number">31</span> - <span class="number">1</span>) : <span class="built_in">Math</span>.max(res, -(<span class="number">2</span>**<span class="number">31</span>))</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<h2 id="9、回文数"><a href="#9、回文数" class="headerlink" title="9、回文数"></a>9、回文数</h2><p>题目：判断一个整数是否是回文数。回文数是指正序（从左向右）和倒序（从右向左）读都是一样的整数。</p>
<p>思路：跟前面的整数反转一样，简单的思路的话，直接变数组之后，使用reverse()方法之后判断即可；同样也有数学方法来解决这个问题。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//直接用reverse()</span></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">&#123;number&#125;</span> <span class="variable">x</span></span></span></span><br><span class="line"><span class="comment"> * <span class="doctag">@return <span class="type">&#123;boolean&#125;</span></span></span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">var</span> isPalindrome = <span class="function"><span class="keyword">function</span>(<span class="params">x</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> x === <span class="built_in">Number</span>(x.toString().split(<span class="string">''</span>).reverse().join(<span class="string">''</span>))</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="comment">//利用数学方法来一步步求余</span></span><br><span class="line"><span class="keyword">var</span> isPalindrome = <span class="function"><span class="keyword">function</span>(<span class="params">x</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (x &lt; <span class="number">0</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">let</span> result = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">let</span> value = x;</span><br><span class="line">    <span class="keyword">while</span> (x !== <span class="number">0</span>) &#123;</span><br><span class="line">        result = result * <span class="number">10</span> + x % <span class="number">10</span>;</span><br><span class="line">        x = (x / <span class="number">10</span>) | <span class="number">0</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span> (value = result) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="10、正则表达式匹配"><a href="#10、正则表达式匹配" class="headerlink" title="10、正则表达式匹配"></a>10、正则表达式匹配</h2><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> isMatch = <span class="function">(<span class="params">s, p</span>) =&gt;</span> &#123;</span><br><span class="line">  <span class="keyword">if</span> (s == <span class="literal">null</span> || p == <span class="literal">null</span>) <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">const</span> sLen = s.length, pLen = p.length;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">const</span> dp = <span class="keyword">new</span> <span class="built_in">Array</span>(sLen + <span class="number">1</span>);</span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; dp.length; i++) &#123;</span><br><span class="line">    dp[i] = <span class="keyword">new</span> <span class="built_in">Array</span>(pLen + <span class="number">1</span>).fill(<span class="literal">false</span>); <span class="comment">// 将项默认为false</span></span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">// base case</span></span><br><span class="line">  dp[<span class="number">0</span>][<span class="number">0</span>] = <span class="literal">true</span>;</span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">let</span> j = <span class="number">1</span>; j &lt; pLen + <span class="number">1</span>; j++) &#123;</span><br><span class="line">    <span class="keyword">if</span> (p[j - <span class="number">1</span>] == <span class="string">"*"</span>) dp[<span class="number">0</span>][j] = dp[<span class="number">0</span>][j - <span class="number">2</span>];</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">// 迭代</span></span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">1</span>; i &lt; sLen + <span class="number">1</span>; i++) &#123;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> j = <span class="number">1</span>; j &lt; pLen + <span class="number">1</span>; j++) &#123;</span><br><span class="line"></span><br><span class="line">      <span class="keyword">if</span> (s[i - <span class="number">1</span>] == p[j - <span class="number">1</span>] || p[j - <span class="number">1</span>] == <span class="string">"."</span>) &#123;</span><br><span class="line">        dp[i][j] = dp[i - <span class="number">1</span>][j - <span class="number">1</span>];</span><br><span class="line">      &#125; <span class="keyword">else</span> <span class="keyword">if</span> (p[j - <span class="number">1</span>] == <span class="string">"*"</span>) &#123;</span><br><span class="line">        <span class="keyword">if</span> (s[i - <span class="number">1</span>] == p[j - <span class="number">2</span>] || p[j - <span class="number">2</span>] == <span class="string">"."</span>) &#123;</span><br><span class="line">          dp[i][j] = dp[i][j - <span class="number">2</span>] || dp[i - <span class="number">1</span>][j - <span class="number">2</span>] || dp[i - <span class="number">1</span>][j];</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">          dp[i][j] = dp[i][j - <span class="number">2</span>];</span><br><span class="line">        &#125;</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> dp[sLen][pLen]; <span class="comment">// 长sLen的s串 是否匹配 长pLen的p串</span></span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<h2 id="11、盛水最多的容器"><a href="#11、盛水最多的容器" class="headerlink" title="11、盛水最多的容器"></a>11、盛水最多的容器</h2><p>题目：给你 n 个非负整数 a1，a2，…，an，每个数代表坐标中的一个点 (i, ai) 。在坐标内画 n 条垂直线，垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0)。找出其中的两条线，使得它们与 x 轴共同构成的容器可以容纳最多的水。说明：你不能倾斜容器，且 n 的值至少为 2。</p>
<p>示例：输入：[1,8,6,2,5,4,8,3,7]；输出：49 ；解释：图中垂直线代表输入数组 [1,8,6,2,5,4,8,3,7]。在此情况下，容器能够容纳水（表示为蓝色部分）的最大值为 49。</p>
<p>思路：其实是一个滑动窗口(双指针)类型的题目，暴力法：即穷举所有可能，分别计算面积并保存最大值。</p>
<p>双指针法：从左右两侧开始，将较矮柱子的指针进行移动，而先不移动高柱子的指针，原因：矮柱子选取后如果移动高柱子的话面积是一定会减小的，因为长度距离在变小的时候，此时高度只能小于或等于矮的柱子。因此只能移动矮的柱子这边才有可能使得高度比矮柱子大。所以，每次都移动的是高柱子的指针。这种方法其可以看作是暴力法的剪枝，而不是传统的滑动窗口。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">&#123;number[]&#125;</span> <span class="variable">height</span></span></span></span><br><span class="line"><span class="comment"> * <span class="doctag">@return <span class="type">&#123;number&#125;</span></span></span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">const</span> maxArea = <span class="function"><span class="keyword">function</span>(<span class="params">height</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">let</span> left = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">let</span> right = height.length - <span class="number">1</span>;</span><br><span class="line">    <span class="keyword">let</span> ans = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">while</span> (left &lt; right) &#123;</span><br><span class="line">        <span class="keyword">let</span> height1 = <span class="built_in">Math</span>.min(height[left], height[right]);</span><br><span class="line">        <span class="keyword">let</span> aquare = height1 * (right - left);</span><br><span class="line">        ans = <span class="built_in">Math</span>.max(ans, aquare);</span><br><span class="line">        <span class="keyword">if</span> (height[left] &lt; height[right]) &#123;</span><br><span class="line">            left++;</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            right--;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> ans;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="12、整数转罗马数字"><a href="#12、整数转罗马数字" class="headerlink" title="12、整数转罗马数字"></a>12、整数转罗马数字</h2><p>思路：整数转罗马数字，比罗马数字转整数要简洁一些，同样关键在于求余的操作。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">&#123;number&#125;</span> <span class="variable">num</span></span></span></span><br><span class="line"><span class="comment"> * <span class="doctag">@return <span class="type">&#123;string&#125;</span></span></span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">var</span> intToRoman = <span class="function"><span class="keyword">function</span>(<span class="params">num</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> Q = [<span class="string">""</span>, <span class="string">"M"</span>, <span class="string">"MM"</span>, <span class="string">"MMM"</span>];</span><br><span class="line">    <span class="keyword">var</span> B = [<span class="string">""</span>, <span class="string">"C"</span>, <span class="string">"CC"</span>, <span class="string">"CCC"</span>, <span class="string">"CD"</span>, <span class="string">"D"</span>, <span class="string">"DC"</span>, <span class="string">"DCC"</span>, <span class="string">"DCCC"</span>, <span class="string">"CM"</span>];</span><br><span class="line">    <span class="keyword">var</span> S = [<span class="string">""</span>, <span class="string">"X"</span>, <span class="string">"XX"</span>, <span class="string">"XXX"</span>, <span class="string">"XL"</span>, <span class="string">"L"</span>, <span class="string">"LX"</span>, <span class="string">"LXX"</span>, <span class="string">"LXXX"</span>, <span class="string">"XC"</span>];</span><br><span class="line">    <span class="keyword">var</span> G = [<span class="string">""</span>, <span class="string">"I"</span>, <span class="string">"II"</span>, <span class="string">"III"</span>, <span class="string">"IV"</span>, <span class="string">"V"</span>, <span class="string">"VI"</span>, <span class="string">"VII"</span>, <span class="string">"VIII"</span>, <span class="string">"IX"</span>];</span><br><span class="line">    <span class="keyword">return</span> Q[<span class="built_in">Math</span>.floor(num/<span class="number">1000</span>)] + B[<span class="built_in">Math</span>.floor((num%<span class="number">1000</span>)/<span class="number">100</span>)] + S[<span class="built_in">Math</span>.floor((num%<span class="number">100</span>)/<span class="number">10</span>)] + G[num%<span class="number">10</span>];</span><br><span class="line">&#125;;</span><br><span class="line"><span class="comment">//利用Math.floor来直接取整数部分，而不是四舍五入</span></span><br></pre></td></tr></table></figure>

<h2 id="13、罗马数字转整数"><a href="#13、罗马数字转整数" class="headerlink" title="13、罗马数字转整数"></a>13、罗马数字转整数</h2><p>思路：罗马数字转整数，首先将所有的组合可能性列出并添加到哈希表中</p>
<p>然后对字符串进行遍历，由于组合只有两种，一种是 1 个字符，一种是 2 个字符，其中 2 个字符优先于 1 个字符</p>
<p>先判断两个字符的组合在哈希表中是否存在，存在则将值取出加到结果 ans 中，并向后移2个字符。不存在则将判断当前 1 个字符是否存在，存在则将值取出加到结果 ans 中，并向后移 1 个字符，遍历结束返回结果 ans。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> romanToInt = <span class="function"><span class="keyword">function</span>(<span class="params">s</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">const</span> map = &#123;</span><br><span class="line">        I : <span class="number">1</span>,</span><br><span class="line">        IV: <span class="number">4</span>,</span><br><span class="line">        V: <span class="number">5</span>,</span><br><span class="line">        IX: <span class="number">9</span>,</span><br><span class="line">        X: <span class="number">10</span>,</span><br><span class="line">        XL: <span class="number">40</span>,</span><br><span class="line">        L: <span class="number">50</span>,</span><br><span class="line">        XC: <span class="number">90</span>,</span><br><span class="line">        C: <span class="number">100</span>,</span><br><span class="line">        CD: <span class="number">400</span>,</span><br><span class="line">        D: <span class="number">500</span>,</span><br><span class="line">        CM: <span class="number">900</span>,</span><br><span class="line">        M: <span class="number">1000</span></span><br><span class="line">    &#125;;</span><br><span class="line">    <span class="keyword">let</span> ans = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">for</span>(<span class="keyword">let</span> i = <span class="number">0</span>;i &lt; s.length;) &#123;</span><br><span class="line">        <span class="keyword">if</span>(i + <span class="number">1</span> &lt; s.length &amp;&amp; map[s.substring(i, i+<span class="number">2</span>)]) &#123;</span><br><span class="line">            ans += map[s.substring(i, i+<span class="number">2</span>)];</span><br><span class="line">            i += <span class="number">2</span>;</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            ans += map[s.substring(i, i+<span class="number">1</span>)];</span><br><span class="line">            i ++;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> ans;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<h2 id="14、最长公共前缀"><a href="#14、最长公共前缀" class="headerlink" title="14、最长公共前缀"></a>14、最长公共前缀</h2><p>题目：编写一个函数来查找字符串数组中的最长公共前缀。如果不存在公共前缀，返回空字符串 <code>&quot;&quot;</code>。</p>
<p>思路：很简单的题目，一个个的依次找最长公共前缀，先比较前两个，再用得出的公共前缀来匹配下一个；因此需要两层for循环，第一层，用于获取各个字符串，第二层对比每个字符串的各个字符。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">&#123;string[]&#125;</span> <span class="variable">strs</span></span></span></span><br><span class="line"><span class="comment"> * <span class="doctag">@return <span class="type">&#123;string&#125;</span></span></span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">var</span> longestCommonPrefix = <span class="function"><span class="keyword">function</span>(<span class="params">strs</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (strs.length == <span class="number">0</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="string">""</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">let</span> res = strs[<span class="number">0</span>];</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">1</span>; i &lt; strs.length; i++) &#123;</span><br><span class="line">        <span class="keyword">let</span> compare = res;</span><br><span class="line">        res = <span class="string">""</span>;</span><br><span class="line">        <span class="comment">//前两个先比较,每次比较前修改compare,并重置res</span></span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">let</span> j = <span class="number">0</span>; (j &lt; strs[i].length) &amp;&amp; (j &lt; compare.length); j++) &#123;</span><br><span class="line">            <span class="keyword">if</span> (strs[i][j] === compare[j]) &#123;</span><br><span class="line">                res = res + compare[j];</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span> (res == <span class="string">""</span>) &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="string">""</span>;</span><br><span class="line">        <span class="comment">//提前退出的条件，剪枝j</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> res;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="15、三数之和"><a href="#15、三数之和" class="headerlink" title="15、三数之和"></a>15、三数之和</h2><p>给你一个包含 n 个整数的数组 nums，判断 nums 中是否存在三个元素 a，b，c ，使得 a + b + c = 0 ？请你找出所有满足条件且不重复的三元组。注意：答案中不可以包含重复的三元组。</p>
<p>思路：关键在于如何保证不重复，用常规思路的话，先用三层for循环，之后再用哈希表去重；换一个思路，我们保持三重循环的大框架不变，只需要保证：第二重循环枚举到的元素不小于当前第一重循环枚举到的元素；第三重循环枚举到的元素不小于当前第二重循环枚举到的元素。即这样就只有一种顺序被枚举了，可以先排序，然后再查找。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> threeSum = <span class="function"><span class="keyword">function</span>(<span class="params">nums</span>) </span>&#123;</span><br><span class="line">    nums.sort(<span class="function">(<span class="params">a, b</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> (a - b);</span><br><span class="line">    &#125;);</span><br><span class="line">    <span class="keyword">let</span> res = [];</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; nums.length; i++) &#123;</span><br><span class="line">        <span class="keyword">if</span> (nums[i] &gt; <span class="number">0</span>) &#123;</span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">        &#125;<span class="comment">//在算法范畴上，进行逻辑的剪枝，此时后续不可能成立</span></span><br><span class="line">        <span class="keyword">let</span> target = -nums[i];</span><br><span class="line">        <span class="keyword">if</span> ((target + nums[i - <span class="number">1</span>] == <span class="number">0</span>) &amp;&amp; i &gt; <span class="number">0</span>) &#123;</span><br><span class="line">            <span class="keyword">continue</span>;</span><br><span class="line">            <span class="comment">//从左往右遍历，此时遇到重复的则直接跳过，使用continue到for的下一个</span></span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">//找到一个后，后续的使用双指针来遍历查找，同时去重</span></span><br><span class="line">        <span class="keyword">let</span> left = i + <span class="number">1</span>;</span><br><span class="line">        <span class="keyword">let</span> right = nums.length - <span class="number">1</span>;</span><br><span class="line">        <span class="keyword">while</span> (left &lt; right) &#123;</span><br><span class="line">            <span class="keyword">let</span> n2 = nums[left];</span><br><span class="line">            <span class="keyword">let</span> n3 = nums[right];</span><br><span class="line">            <span class="keyword">if</span> (n2 + n3 === target) &#123;</span><br><span class="line">                res.push([nums[i], n2, n3]);</span><br><span class="line">                <span class="keyword">while</span> (left &lt; right &amp;&amp; nums[left] === n2) left++;</span><br><span class="line">                <span class="comment">//去重复，后面有相同的则这里直接left++跳过去</span></span><br><span class="line">                <span class="keyword">while</span> (left &lt; right &amp;&amp; nums[right] === n3) right++;</span><br><span class="line">                <span class="comment">//这里在去重时，不要忘记基本的left &lt; right</span></span><br><span class="line">            &#125; <span class="keyword">else</span> <span class="keyword">if</span>(n2 + n3 &lt; target) &#123;</span><br><span class="line">                left++;</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                right--;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> res;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="16、最接近的三数之和"><a href="#16、最接近的三数之和" class="headerlink" title="16、最接近的三数之和"></a>16、最接近的三数之和</h2><p>题目：给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数，使得它们的和与 target 最接近。返回这三个数的和。假定每组输入只存在唯一答案。</p>
<p>思路：同样的思路，排序加双指针的做法能够很好地判断该如何去判断怎么去移动；同样，本题中不需要去考虑重复的问题了。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> threeSumClosest = <span class="function"><span class="keyword">function</span>(<span class="params">nums, target</span>) </span>&#123;</span><br><span class="line">    nums.sort(<span class="function">(<span class="params">a, b</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> (a - b);</span><br><span class="line">    &#125;);</span><br><span class="line">    <span class="keyword">let</span> ans = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">let</span> compare = <span class="literal">Infinity</span>;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; nums.length; i++) &#123;</span><br><span class="line">        <span class="keyword">let</span> left = i + <span class="number">1</span>;</span><br><span class="line">        <span class="keyword">let</span> right = nums.length - <span class="number">1</span>;</span><br><span class="line">        <span class="keyword">while</span> (left &lt; right) &#123;</span><br><span class="line">            <span class="keyword">let</span> compare2 = target - nums[left] - nums[right] - nums[i];</span><br><span class="line">            <span class="keyword">if</span> (<span class="built_in">Math</span>.abs(compare2) &lt; compare) &#123;</span><br><span class="line">                ans = nums[i] + nums[right] + nums[left];</span><br><span class="line">                compare = <span class="built_in">Math</span>.abs(compare2)</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">if</span> (compare2 &lt; <span class="number">0</span>) &#123;</span><br><span class="line">                right--;</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                left++;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> ans;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="17、电话号码的组合"><a href="#17、电话号码的组合" class="headerlink" title="17、电话号码的组合"></a>17、电话号码的组合</h2><p>给定一个仅包含数字 <code>2-9</code> 的字符串，返回所有它能表示的字母组合。给出数字到字母的映射如下（与电话按键相同）。注意 1 不对应任何字母。</p>
<p>思路：看上去十分容易，本质是一个三叉树的遍历方法，可以用BFS或者DFS。由这个题，我们可以先引申一下深度遍历和广度遍历的思路逻辑与基本方法。</p>
<p>1、DFS回溯（回溯是一种算法思想，一般可以用递归来实现。通俗点讲回溯就是一种试探,类似于穷举,但回溯有“剪枝”功能,）</p>
<p>回溯本质是暴力搜索，在问题的解空间树中，用 DFS 的方式，从根节点出发搜索整个解空间。如果要找出所有的解，则要搜索整个子树，如果只用找出一个解，则搜到一个解就可以结束搜索。类似「找出所有可能的组合」的问题，适合回溯算法。</p>
<p>回溯类题目，有三个关键点：</p>
<p>(1).选择:决定了你每个节点有哪些分支，可以帮助你构建出解的空间树。</p>
<p>(2).约束条件:用来剪枝，剪去不满足约束条件的子树，避免无效的搜索。</p>
<p>(3).目标:决定了何时捕获解，或者剪去得不到解的子树，提前回溯。</p>
<p>回溯法实质:它的求解过程实质上是先序遍历一棵“状态树”的过程。只不过，这棵树不是遍历前预先建立的，而是隐含在遍历过程中。如果认识到这点，很多问题的递归过程设计也就迎刃而解了。【回溯与递归的区别】回溯这个算法思想可以由递归这个算法结构来实现</p>
<p>我们构建一个递归来实现DFS，。递归的关键：递归关系与递归终止条件。（其他的扔给递归）</p>
<p>1、找整个递归的终止条件：递归应该在什么时候结束？2、找返回值：应该给下一级返回什么信息？3、本级递归应该做什么：在这一级递归中，应该完成什么任务？</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> letterCombinations = <span class="function">(<span class="params">digits</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">if</span> (digits.length === <span class="number">0</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> [];</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">const</span> res = [];</span><br><span class="line">    <span class="keyword">const</span> map = <span class="keyword">new</span> <span class="built_in">Map</span>([[<span class="string">'2'</span>,<span class="string">'abc'</span>], [<span class="string">'3'</span>,<span class="string">'def'</span>],[<span class="string">'4'</span>,<span class="string">'ghi'</span>],[<span class="string">'5'</span>,<span class="string">'jkl'</span>],[<span class="string">'6'</span>,<span class="string">'mno'</span>],[<span class="string">'7'</span>,<span class="string">'pqrs'</span>],[<span class="string">'8'</span>,<span class="string">'tuv'</span>],[<span class="string">'9'</span>,<span class="string">'wxyz'</span>]]);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">const</span> dfs = <span class="function">(<span class="params">curStr, i</span>) =&gt;</span> &#123;<span class="comment">//递归的传递参数包括，当前已经遍历树的结果、以及层数i</span></span><br><span class="line">        <span class="keyword">if</span> (i &gt; digits.length - <span class="number">1</span>) &#123;</span><br><span class="line">            res.push(curStr);</span><br><span class="line">            <span class="keyword">return</span>;<span class="comment">//一个树的递归分支结束</span></span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">let</span> letters = map.get(digits[i]);</span><br><span class="line">        <span class="keyword">for</span> (j <span class="keyword">of</span> letters) &#123;</span><br><span class="line">            <span class="comment">//for in 用于遍历对象,for of用于遍历有Iterator接口的对象,</span></span><br><span class="line">            dfs(curStr, i+<span class="number">1</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    dfs(<span class="string">""</span>, <span class="number">0</span>);</span><br><span class="line">    <span class="keyword">return</span> res;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>2、BFS广度搜索的方法</p>
<p>BFS通常是维护一个队列，即一层层地进行遍历，每次将对应层数的叶子加到之前层上，这里可以使用队列先进先出来解决，先进先出，依次地每次更新对应的下一层的结果。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">&#123;string&#125;</span> <span class="variable">digits</span></span></span></span><br><span class="line"><span class="comment"> * <span class="doctag">@return <span class="type">&#123;string[]&#125;</span></span></span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">const</span> letterCombinations = <span class="function">(<span class="params">digits</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">if</span> (digits.length == <span class="number">0</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> [];</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">let</span> res = [];</span><br><span class="line">    <span class="keyword">let</span> map = <span class="keyword">new</span> <span class="built_in">Map</span>([[<span class="string">'2'</span>,<span class="string">'abc'</span>], [<span class="string">'3'</span>,<span class="string">'def'</span>],[<span class="string">'4'</span>,<span class="string">'ghi'</span>],[<span class="string">'5'</span>,<span class="string">'jkl'</span>],[<span class="string">'6'</span>,<span class="string">'mno'</span>],[<span class="string">'7'</span>,<span class="string">'pqrs'</span>],[<span class="string">'8'</span>,<span class="string">'tuv'</span>],[<span class="string">'9'</span>,<span class="string">'wxyz'</span>]]);</span><br><span class="line">    <span class="keyword">let</span> queue = [];</span><br><span class="line">    queue.push(<span class="string">''</span>);</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; digits.length; i++) &#123;<span class="comment">//bfs二叉树的层数，就是digits的长度</span></span><br><span class="line">        <span class="keyword">let</span> levelSize = queue.length;<span class="comment">//获取当前层的节点数，从而能逐个让当前层节点出列，更新接上对应后续节点后再依次入列</span></span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">let</span> j = <span class="number">0</span>; j &lt; levelSize; j++) &#123;</span><br><span class="line">            <span class="keyword">let</span> curStr = queue.shift(); <span class="comment">//模拟队列</span></span><br><span class="line">            <span class="keyword">let</span> letters = map.get(digits[i]);</span><br><span class="line">            <span class="keyword">for</span> (<span class="keyword">let</span> k <span class="keyword">of</span> letters) &#123;</span><br><span class="line">                queue.push(curStr + k);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> queue;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="18、四数之和"><a href="#18、四数之和" class="headerlink" title="18、四数之和"></a>18、四数之和</h2><p>题目：给定一个包含 n 个整数的数组 nums 和一个目标值 target，判断 nums 中是否存在四个元素 a，b，c 和 d ，使得 a + b + c + d 的值与 target 相等？找出所有满足条件且不重复的四元组</p>
<p>思路：其实跟前面的三数之和思路一样，后面两个数可以用双指针法来进行枚举；而前面两个数只能通过两层的for循环来实现。同样，先对数组进行排序，且添加每个数时都要进行重复判断。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> fourSum = <span class="function"><span class="keyword">function</span>(<span class="params">nums, target</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">const</span> quadruplets = [];</span><br><span class="line">    <span class="keyword">if</span> (nums.length &lt; <span class="number">4</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> quadruplets;</span><br><span class="line">    &#125;</span><br><span class="line">    nums.sort(<span class="function">(<span class="params">x, y</span>) =&gt;</span> x - y);</span><br><span class="line">    <span class="keyword">const</span> length = nums.length;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; length - <span class="number">3</span>; i++) &#123;</span><br><span class="line">        <span class="keyword">if</span> (i &gt; <span class="number">0</span> &amp;&amp; nums[i] === nums[i - <span class="number">1</span>]) &#123;</span><br><span class="line">            <span class="keyword">continue</span>;<span class="comment">//从左往右遍历，有跟上一条重复的则跳过</span></span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span> (nums[i] + nums[i + <span class="number">1</span>] + nums[i + <span class="number">2</span>] + nums[i + <span class="number">3</span>] &gt; target) &#123;</span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span> (nums[i] + nums[length - <span class="number">3</span>] + nums[length - <span class="number">2</span>] + nums[length - <span class="number">1</span>] &lt; target) &#123;</span><br><span class="line">            <span class="keyword">continue</span>;<span class="comment">//上面两种情况都是剪枝，以减少事件复杂度</span></span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">let</span> j = i + <span class="number">1</span>; j &lt; length - <span class="number">2</span>; j++) &#123;</span><br><span class="line">            <span class="keyword">if</span> (j &gt; i + <span class="number">1</span> &amp;&amp; nums[j] === nums[j - <span class="number">1</span>]) &#123;</span><br><span class="line">                <span class="keyword">continue</span>;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">if</span> (nums[i] + nums[j] + nums[j + <span class="number">1</span>] + nums[j + <span class="number">2</span>] &gt; target) &#123;</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">if</span> (nums[i] + nums[j] + nums[length - <span class="number">2</span>] + nums[length - <span class="number">1</span>] &lt; target) &#123;</span><br><span class="line">                <span class="keyword">continue</span>;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">let</span> left = j + <span class="number">1</span>, right = length - <span class="number">1</span>;</span><br><span class="line">            <span class="keyword">while</span> (left &lt; right) &#123;</span><br><span class="line">                <span class="keyword">const</span> sum = nums[i] + nums[j] + nums[left] + nums[right];</span><br><span class="line">                <span class="keyword">if</span> (sum === target) &#123;</span><br><span class="line">                    quadruplets.push([nums[i], nums[j], nums[left], nums[right]]);</span><br><span class="line">                    <span class="keyword">while</span> (left &lt; right &amp;&amp; nums[left] === nums[left + <span class="number">1</span>]) &#123;</span><br><span class="line">                        left++;</span><br><span class="line">                    &#125;</span><br><span class="line">                    left++;</span><br><span class="line">                    <span class="keyword">while</span> (left &lt; right &amp;&amp; nums[right] === nums[right - <span class="number">1</span>]) &#123;</span><br><span class="line">                        right--;</span><br><span class="line">                    &#125;</span><br><span class="line">                    right--;</span><br><span class="line">                &#125; <span class="keyword">else</span> <span class="keyword">if</span> (sum &lt; target) &#123;</span><br><span class="line">                    left++;</span><br><span class="line">                &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                    right--;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> quadruplets;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<h2 id="19、删除链表的倒数第N个结点"><a href="#19、删除链表的倒数第N个结点" class="headerlink" title="19、删除链表的倒数第N个结点"></a>19、删除链表的倒数第N个结点</h2><p>题目:给你一个链表，删除链表的倒数第 <code>n</code> 个结点，并且返回链表的头结点。进阶：你能尝试使用一趟扫描实现吗？</p>
<p>思路：不要求时间复杂度的话，先扫一遍来确定链表的长度，而后再根据长度找到倒数第N个结点；要使用一趟扫描实现的话，可以使用双指针来进行。第一个指针比第二个快n个，这样第二个指向尾节点时，则第一个指向要删除的结点。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> removeNthFromEnd = <span class="function"><span class="keyword">function</span>(<span class="params">head, n</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">let</span> start = <span class="keyword">new</span> ListNode;</span><br><span class="line">    <span class="comment">//一般先定义一个空结点放到现有的头节点前面，之后以该空结点作链表处理，从而能够避免因链表长度不够导致的报错</span></span><br><span class="line">    start.next = head;</span><br><span class="line">    <span class="keyword">let</span> left = start;</span><br><span class="line">    <span class="keyword">let</span> right = start;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; n; i++) &#123;</span><br><span class="line">        right = right.next;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">while</span> (right.next != <span class="literal">null</span>) &#123;</span><br><span class="line">        left = left.next;</span><br><span class="line">        right = right.next;</span><br><span class="line">    &#125;</span><br><span class="line">    left.next = left.next.next;</span><br><span class="line">    <span class="keyword">return</span> start.next;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<h2 id="20、有效的括号"><a href="#20、有效的括号" class="headerlink" title="20、有效的括号"></a>20、有效的括号</h2><p>题目：给定一个只包括 ‘(‘，’)’，’{‘，’}’，’[‘，’]’ 的字符串，判断字符串是否有效。有效字符串需满足：左括号必须用相同类型的右括号闭合。左括号必须以正确的顺序闭合。注意空字符串可被认为是有效字符串。</p>
<p>思路：类似于栈的操作，判断很简单，这里就不赘述了。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">&#123;string&#125;</span> <span class="variable">s</span></span></span></span><br><span class="line"><span class="comment"> * <span class="doctag">@return <span class="type">&#123;boolean&#125;</span></span></span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">&#123;string&#125;</span> <span class="variable">s</span></span></span></span><br><span class="line"><span class="comment"> * <span class="doctag">@return <span class="type">&#123;boolean&#125;</span></span></span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">var</span> isValid = <span class="function"><span class="keyword">function</span>(<span class="params">s</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (s.length == <span class="number">0</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">let</span> compare = [];</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; s.length; i++) &#123;</span><br><span class="line">        <span class="keyword">if</span> (s[i] === <span class="string">"("</span> || s[i] === <span class="string">"["</span> || s[i] === <span class="string">"&#123;"</span>) &#123;</span><br><span class="line">            compare.push(s[i]);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">else</span> <span class="keyword">if</span> (s[i] === <span class="string">")"</span>) &#123;</span><br><span class="line">            <span class="keyword">let</span> a = compare.pop();</span><br><span class="line">            <span class="keyword">if</span> (a !== <span class="string">"("</span>) &#123;</span><br><span class="line">                <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">else</span> <span class="keyword">if</span> (s[i] === <span class="string">"]"</span>) &#123;</span><br><span class="line">            <span class="keyword">let</span> a = compare.pop();</span><br><span class="line">            <span class="keyword">if</span> (a !== <span class="string">"["</span>) &#123;</span><br><span class="line">                <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">else</span> <span class="keyword">if</span> (s[i] === <span class="string">"&#125;"</span>) &#123;</span><br><span class="line">            <span class="keyword">let</span> a = compare.pop();</span><br><span class="line">            <span class="keyword">if</span> (a !== <span class="string">"&#123;"</span>) &#123;</span><br><span class="line">                <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span> (compare.length == <span class="number">0</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>


    </div>
    
    
    
    
    <div>
      
        <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------本文结束<i class="fa fa-paw"></i>感谢您的阅读-------------</div>
    
</div>

      
    </div>
        <div class="reward-container">
  <div>坚持原创技术分享，您的支持将鼓励我继续创作！</div>
  <button onclick="var qr = document.getElementById('qr'); qr.style.display = (qr.style.display === 'none') ? 'block' : 'none';">
    打赏
  </button>
  <div id="qr" style="display: none;">
      
      <div style="display: inline-block;">
        <img src="/images/alipay.png" alt="Li Yudong 支付宝">
        <p>支付宝</p>
      </div>

  </div>
</div>

        

<div>
<ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者： </strong>Li Yudong
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="http://example.com/2021/09/06/%E7%AE%97%E6%B3%95/JS%E5%8A%9B%E6%89%A3%E5%88%B7%E9%A2%98%E8%AE%B0%EF%BC%88%E4%B8%80%EF%BC%89/" title="JS力扣刷题记（一）">http://example.com/2021/09/06/算法/JS力扣刷题记（一）/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="noopener" target="_blank"><i class="fab fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！
  </li>
</ul>
</div>

    
      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/%E5%8A%9B%E6%89%A3/" rel="tag"># 力扣</a>
          </div>
    
        

    
        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2021/08/24/node/egg-node%E5%AE%9E%E6%88%98/" rel="prev" title="数据库">
      <i class="fa fa-chevron-left"></i> 数据库
    </a></div>
      <div class="post-nav-item">
    <a href="/2021/09/06/%E7%AE%97%E6%B3%95/JS%E5%8A%9B%E6%89%A3%E5%88%B7%E9%A2%98%E8%AE%B0%EF%BC%88%E4%BA%8C%EF%BC%89/" rel="next" title="JS力扣刷题记（二）">
      JS力扣刷题记（二） <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#前言"><span class="nav-number">1.</span> <span class="nav-text">前言</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#1、两数之和"><span class="nav-number">2.</span> <span class="nav-text">1、两数之和</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2、两数相加"><span class="nav-number">3.</span> <span class="nav-text">2、两数相加</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3、无重复字符的最长子串"><span class="nav-number">4.</span> <span class="nav-text">3、无重复字符的最长子串</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4、寻找正序数组的两个中位数"><span class="nav-number">5.</span> <span class="nav-text">4、寻找正序数组的两个中位数</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#5、最长回文子串"><span class="nav-number">6.</span> <span class="nav-text">5、最长回文子串</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#6、Z字形变换"><span class="nav-number">7.</span> <span class="nav-text">6、Z字形变换</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#7、整数反转"><span class="nav-number">8.</span> <span class="nav-text">7、整数反转</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#8、字符串转整数"><span class="nav-number">9.</span> <span class="nav-text">8、字符串转整数</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#9、回文数"><span class="nav-number">10.</span> <span class="nav-text">9、回文数</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#10、正则表达式匹配"><span class="nav-number">11.</span> <span class="nav-text">10、正则表达式匹配</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#11、盛水最多的容器"><span class="nav-number">12.</span> <span class="nav-text">11、盛水最多的容器</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#12、整数转罗马数字"><span class="nav-number">13.</span> <span class="nav-text">12、整数转罗马数字</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#13、罗马数字转整数"><span class="nav-number">14.</span> <span class="nav-text">13、罗马数字转整数</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#14、最长公共前缀"><span class="nav-number">15.</span> <span class="nav-text">14、最长公共前缀</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#15、三数之和"><span class="nav-number">16.</span> <span class="nav-text">15、三数之和</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#16、最接近的三数之和"><span class="nav-number">17.</span> <span class="nav-text">16、最接近的三数之和</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#17、电话号码的组合"><span class="nav-number">18.</span> <span class="nav-text">17、电话号码的组合</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#18、四数之和"><span class="nav-number">19.</span> <span class="nav-text">18、四数之和</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#19、删除链表的倒数第N个结点"><span class="nav-number">20.</span> <span class="nav-text">19、删除链表的倒数第N个结点</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#20、有效的括号"><span class="nav-number">21.</span> <span class="nav-text">20、有效的括号</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="Li Yudong"
      src="/images/author.jpg">
  <p class="site-author-name" itemprop="name">Li Yudong</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">95</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">14</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">18</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/tiarmor1" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;tiarmor1" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="mailto:1157019137@qq.com" title="E-Mail → mailto:1157019137@qq.com" rel="noopener" target="_blank"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
      </span>
  </div>
  <div class="cc-license motion-element" itemprop="license">
    <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" class="cc-opacity" rel="noopener" target="_blank"><img src="/images/cc-by-nc-sa.svg" alt="Creative Commons"></a>
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 2020 – 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Li Yudong</span>
</div>

        








      </div>
    </footer>
  </div>

  
  
  <script color='0,0,0' opacity='0.5' zIndex='-1' count='150' src="/lib1/canvas-nest/canvas-nest.min.js"></script>
  <script src="/lib1/anime.min.js"></script>
  <script src="/lib1/velocity/velocity.min.js"></script>
  <script src="/lib1/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  




  
<script src="/js/local-search.js"></script>













  

  

  
   <canvas class="fireworks" style="position: fixed;left: 0;top: 0;z-index: 1; pointer-events: none;" ></canvas> 
   <script type="text/javascript" src="//cdn.bootcss.com/animejs/2.2.0/anime.min.js"></script> 
   <script type="text/javascript" src="/js/fireworks.js"></script>
  
</body>
</html>

